Vue.component('hc-lang-editor', {
    name: 'hc-lang-editor',
    data: function() {
        return {
            valueInEditor: '',
            editor: null,
        }
    },
    props: {
        lang: {
            type: [String],
            default: 'json', //support other, eg: sql
        },
        value: {
            type: [String, Object],
            required: true
        },
        readonly: {
            type: Boolean,
            default: false,
        },
        maxlines: {
            type: Number,
            default: 20
        },
        minlines: {
            type: Number,
            default: 12,
        },
    },
    created: function() {
        this.valueInEditor = this.value;
    },
    mounted: function() {
        if (typeof(ace) == 'undefined') {
            console.error('hc-lang-editor component must refer to ace.js');
            return;
        }

        let dom = this.$refs['editor'];
        this.editor = ace.edit(dom, {
            mode: "ace/mode/" + this.lang,
            theme: 'ace/theme/chrome',
            maxLines: this.maxlines,
            minLines: this.minlines,
            readOnly: this.readonly,
            highlightActiveLine: false,
            highlightSelectedWord: false,
            fontSize: 14,
            wrap: true,
            tabSize: 4,
            showLineNumbers: true,
            showGutter: false,
            showPrintMargin: false,
            displayIndentGuides: true,
            fixedWidthGutter: true,
            value: this.value, // this.editor.setValue(this.value);
        });

        this.editor.getSession().on('change', this.handleChange);
    },
    watch: {
        "value": {
            immediate: true,
            handler: function(newVal, oldVal) {
                // console.log('hc-lang-editor watch value',newVal,oldVal,this.valueInEditor);
                if (this.editor != null && this.valueInEditor != newVal) { //block update editor duplicatedly, otherwise cause the wrong cusor location 
                    this.editor.setValue(newVal);
                    this.editor.clearSelection()
                }
            }
        },
        "readonly": {
            immediate: true,
            handler: function(nv, ov) {
                if (this.editor != null)
                    this.editor.setOptions({
                        "readOnly": nv
                    });
            }
        }
    },
    methods: {
        handleChange() {
            this.valueInEditor = this.editor.getSession().getValue();
            this.$emit('input', this.valueInEditor)
        },
    },
    destroyed: function() {
        this.editor.destroy();
        this.editor.container.remove();
    },
    template: `
     <div >
         <pre :readonly='readonly' class='hc-lang-editor' ref='editor'>{{value}}</pre>
     </div>
     `
});
